<script lang="ts" setup>
import { ref, watch } from 'vue';
import { getSysPermissionApi } from '@/common/apis/permission';
import { putSysRoleAssignPremApi } from '@/common/apis/role';
import { message } from 'ant-design-vue';

// 接收父组件传递的 props
const props = defineProps({
    roleDetail: {
        type: Object as () => { permIds: number[]; id: number },
        default: () => ({ permIds: [], id: null }),
    },
});



const open = ref(false); // 控制弹框显示
const selectedPermIds = ref<number[]>([]); // 存储用户选择的权限 ID
const sysPermnData = ref<any[]>([]); // 存储权限点列表

// 显示弹框
const showModal = () => {
    open.value = true;
};

// 处理权限选择
const onClickChecked = (id: number) => {
    const index = selectedPermIds.value.indexOf(id);
    if (index === -1) {
        selectedPermIds.value.push(id); // 添加权限 ID
    } else {
        selectedPermIds.value.splice(index, 1); // 移除权限 ID
    }
};

// 确认分配权限
const handleOk = async () => {
    try {
        const res = await putSysRoleAssignPremApi({
            id: props.roleDetail.id,
            permIds: selectedPermIds.value, // 用户选择的权限 ID
        });
        console.log(res, '分配权限成功');
        message.success('保存成功');
        open.value = false; // 关闭弹框
    } catch (error) {
        console.error('分配权限失败', error);
    }
};

// 获取权限点列表
const getSysPermissionData = async () => {
    const res = await getSysPermissionApi();
    sysPermnData.value = res.data.data;
};

// 监听 roleDetail 的变化
watch(
    () => props.roleDetail,
    (newRoleDetail) => {
        selectedPermIds.value = [...newRoleDetail.permIds]; // 更新选中的权限 ID
        console.log(props.roleDetail, 'roleDetaifdafdafafafdl')

    },
    { immediate: true, deep: true } // 立即执行一次，并深度监听
);



// 暴露 showModal 方法给父组件
defineExpose({
    showModal,
});

// 初始化获取权限点列表
getSysPermissionData();
</script>

<template>
    <div>
        <a-modal v-model:open="open" title="分配权限" @ok="handleOk">
            <div v-for="item in sysPermnData" :key="item.id">
                <a-checkbox :checked="selectedPermIds.includes(item.id)" @change="onClickChecked(item.id)">
                    {{ item.name }}
                </a-checkbox>
            </div>
        </a-modal>
    </div>
</template>